package com.zxp.zxpsmarthomeapk.view.fragment;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.squareup.okhttp.Request;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.BitmapCallback;
import com.zxp.zxpsmarthomeapk.R;
import com.zxp.zxpsmarthomeapk.base.Config;
import com.zxp.zxpsmarthomeapk.communicate.CommunicateServer;
import com.zxp.zxpsmarthomeapk.model.MainItemModel;
import com.zxp.zxpsmarthomeapk.model.WeatherModel;
import com.zxp.zxpsmarthomeapk.util.NetUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 首页Fragment
 */
public class HomePageFragment extends Fragment {

    //-------------界面控件初始化-------------
    @BindView(R.id.topbar_homepage)
    QMUITopBar topbar_homepage;
    /**
     * 时间区段
     */
    @BindView(R.id.tv_time_zone)
    TextView tv_time_zone;
    /**
     * 今日天气图标(优良)
     */
    @BindView(R.id.iv_today_weather_title_imgflag)
    ImageView iv_today_weather_title_imgflag;
    /**
     * 天气标题，例如多云，大雨等
     */
    @BindView(R.id.tv_weather_title)
    TextView tv_weather_title;
    /**
     * 天气图标（云雨标志）
     */
    @BindView(R.id.iv_today_weather_imgflag)
    ImageView iv_today_weather_imgflag;
    /**
     * 高温
     */
    @BindView(R.id.tv_hi_temp)
    TextView tv_hi_temp;
    /**
     * 低温
     */
    @BindView(R.id.tv_lo_temp)
    TextView tv_lo_temp;
    /**
     * 湿度
     */
    @BindView(R.id.tv_weather_hum_content)
    TextView tv_weather_hum_content;
    /**
     * 风力
     */
    @BindView(R.id.tv_weather_wind_content)
    TextView tv_weather_wind_content;
    /**
     * 穿衣指数
     */
    @BindView(R.id.tv_weather_lifestyle)
    TextView tv_weather_lifestyle;
    /**
     * 家居设备
     */
    @BindView(R.id.rv_family_devide)
    RecyclerView rv_family_devide;

    private View view_home_page;
    private Handler mhandler = new Handler();
    private String string_weather_icon_code = null;

    public HomePageFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view_home_page = inflater.inflate(R.layout.fragment_home_page, container, false);
        ButterKnife.bind(this, view_home_page);
        //初始化数据
        initData();
        //初始化界面
        initView();
        return view_home_page;
    }

    private void initData() {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        tv_time_zone.setText(hour > 12 ? "下午好" : "上午好");

        NetUtils.getInstance().getDataAsynFromNet(Config.hefeng_url, new NetUtils.MyNetCall() {
            @Override
            public void success(Call call, Response response) throws IOException {
                String str_res = response.body().string();
                Gson gson = new Gson();
                final WeatherModel weatherModel = gson.fromJson(str_res, WeatherModel.class);
                string_weather_icon_code = weatherModel.getHeWeather6().get(0).getNow().getCond_code();
                //异步显示天气状况图标
                OkHttpUtils.get()
                        .url(Config.hefeng_weather_icon + string_weather_icon_code + ".png")
                        .build()
                        .execute(new BitmapCallback() {
                            @Override
                            public void onError(Request request, Exception e) {
                                Log.e("OkHttpUtil getdata fail", e.getMessage());
                            }

                            @Override
                            public void onResponse(Bitmap bitmap) {
                                iv_today_weather_imgflag.setImageBitmap(bitmap);
                            }
                        });

                mhandler.post(new Runnable() {
                    @Override
                    public void run() {
                        tv_weather_title.setText(weatherModel.getHeWeather6().get(0).getNow().getCond_txt());
                        tv_hi_temp.setText(weatherModel.getHeWeather6().get(0).getDaily_forecast().get(0).getTmp_max() + "℃");
                        tv_lo_temp.setText(weatherModel.getHeWeather6().get(0).getDaily_forecast().get(0).getTmp_min() + "℃");
                        tv_weather_hum_content.setText(weatherModel.getHeWeather6().get(0).getNow().getHum());
                        tv_weather_wind_content.setText(weatherModel.getHeWeather6().get(0).getNow().getWind_sc() + "级");
                        tv_weather_lifestyle.setText("生活指数：" + weatherModel.getHeWeather6().get(0).getLifestyle().get(1).getTxt());
                    }
                });
            }

            @Override
            public void failed(Call call, IOException e) {
                Log.e("NetUtil get data fail", e.getMessage());
            }
        });
//        //异步get天气情况
//        OkHttpUtils
//                .get()
//                .url(Config.hefeng_url)
//                .build()
//                .execute(new StringCallback() {
//                    @Override
//                    public void onError(Request request, Exception e) {
//                        Log.e("get_error", e.getMessage());
//                    }
//
//                    @Override
//                    public void onResponse(String response) {
//                        Gson gson = new Gson();
//                        final WeatherModel weatherModel = gson.fromJson(response, WeatherModel.class);
//                        string_weather_icon_code = weatherModel.getHeWeather6().get(0).getNow().getCond_code();
//                        //异步显示天气状况图标
//                        OkHttpUtils.get()
//                                .url(Config.hefeng_weather_icon + string_weather_icon_code + ".png")
//                                .build()
//                                .execute(new BitmapCallback() {
//                                    @Override
//                                    public void onError(Request request, Exception e) {
//                                    }
//
//                                    @Override
//                                    public void onResponse(Bitmap bitmap) {
//                                        iv_today_weather_imgflag.setImageBitmap(bitmap);
//                                    }
//                                });
//
//                        mhandler.post(new Runnable() {
//                            @Override
//                            public void run() {
//                                tv_weather_title.setText(weatherModel.getHeWeather6().get(0).getNow().getCond_txt());
//                                tv_hi_temp.setText(weatherModel.getHeWeather6().get(0).getDaily_forecast().get(0).getTmp_max() + "℃");
//                                tv_lo_temp.setText(weatherModel.getHeWeather6().get(0).getDaily_forecast().get(0).getTmp_min() + "℃");
//                                tv_weather_hum_content.setText(weatherModel.getHeWeather6().get(0).getNow().getHum());
//                                tv_weather_wind_content.setText(weatherModel.getHeWeather6().get(0).getNow().getWind_sc() + "级");
//                                tv_weather_lifestyle.setText("生活指数：" + weatherModel.getHeWeather6().get(0).getLifestyle().get(1).getTxt());
//                            }
//                        });
//                    }
//                });
    }


    private void initView() {
        CommunicateServer communicateServer = new CommunicateServer();
        communicateServer.setHandler(handler);
        new Thread(communicateServer).start();

        topbar_homepage.setTitle("Smart Home");
        topbar_homepage.addRightImageButton(R.drawable.ic_settings_black_24dp, R.id.topbar_right_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getActivity(), "111", Toast.LENGTH_SHORT).show();
            }
        });

        List<MainItemModel> list_device = new ArrayList<MainItemModel>();
        //=======大门
        MainItemModel mainItemModel0 = new MainItemModel(R.mipmap.img_light_big, "");
        //=======车库
        MainItemModel mainItemModel1 = new MainItemModel(R.mipmap.img_chazuo, "");
        //=======灯光
        MainItemModel mainItemModel2 = new MainItemModel(R.mipmap.img_curtain_big, "");
        //=======电脑
        MainItemModel mainItemModel3 = new MainItemModel(R.mipmap.img_computer, "");
        //=======监控
        MainItemModel mainItemModel4 = new MainItemModel(R.mipmap.img_watch_big, "");
        //=======植物
        MainItemModel mainItemModel5 = new MainItemModel(R.mipmap.img_plant, "");

        list_device.add(mainItemModel0);
        list_device.add(mainItemModel1);
        list_device.add(mainItemModel2);
        list_device.add(mainItemModel3);
        list_device.add(mainItemModel4);
        list_device.add(mainItemModel5);

        rv_family_devide.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        rv_family_devide.setAdapter(new CommonAdapter<MainItemModel>(getActivity(), R.layout.rv_family_device_item, list_device) {
            @Override
            protected void convert(final ViewHolder holder, final MainItemModel mainItemModel, final int position) {
                holder.setImageResource(R.id.iv_item, mainItemModel.getImage_item());
                holder.setOnClickListener(R.id.iv_item, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String str_toast = null;
                        switch (position){
                            case 0:   //大门
                                str_toast = "是否打开大门";
                                break;
                            case 1:   //车库
                                str_toast = "是否打开车库";
                                break;
                            case 2:   //灯光
                                str_toast = "是否打开灯光";
                                break;
                            case 3:   //电脑
                                str_toast = "是否打开电脑";
                                break;
                            case 4:   //监控
                                str_toast = "是否查看监控";
                                break;
                            case 5:   //植物
                                str_toast = "是否查看植物";
                                break;
                            default:break;
                        }
                        Toast.makeText(getActivity(),str_toast,Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        rv_family_devide.setItemAnimator(new DefaultItemAnimator());
//        rv_family_devide.addItemDecoration(new DividerItemDecoration(getActivity(),VERTICAL_LIST));
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
//                    tv_getfrom_esp8266.setText("从模块接收到的数据："+msg.obj);
//                    toast("app接收到模块发送过来的消息");
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }
}
